home *** CD-ROM | disk | FTP | other *** search
/ Power Programmierung / Power-Programmierung (Tewi)(1994).iso / magazine / pctchnqs / 1990 / number2 / count.c < prev    next >
Text File  |  1990-04-04  |  1KB  |  46 lines

  1. /* Example of a .EXE modifying program. Works on itself */ 
  2. /* by incrementing counter every time it's executed.    */
  3.  
  4. #include <stdio.h>
  5. #include <string.h>
  6.  
  7. typedef struct { char marker[7]; int counter; } config_data;
  8. config_data cdat = { "%(@#@)", 0 };
  9.  
  10. long find_data(FILE *f, char *marker)
  11. /* Returns the location of the data, or returns -1 */
  12. {
  13.   long nf = 0;
  14.   int ns = 0;
  15.  
  16.   while(!feof(f)) {
  17.      nf++;
  18.      /* if characters don't match, reset search string */
  19.      if (marker[ns++] != fgetc(f)) ns = 0;
  20.      /* if at end, we have match, so return location */
  21.      if (marker[ns] == 0) return nf-strlen(marker);
  22.   }
  23.   return -1L;
  24. }
  25.  
  26. int main(int argc, char *argv[])
  27. {
  28.   FILE *f;
  29.   long data_locn;
  30.  
  31.   f = fopen(argv[0], "r+b"); /* open up self for update */  
  32.   data_locn = find_data(f, cdat.marker);
  33.   if (data_locn == -1)
  34.      fprintf(stderr, "Oops! Can't find the data!\n");
  35.   else {
  36.      fseek(f, data_locn, 0); /* read data */
  37.      fread(&cdat, sizeof(cdat), 1, f);
  38.      cdat.counter++;         /* increment counter */
  39.      printf("Program has executed %d times\n", cdat.counter);    
  40.      fseek(f, data_locn, 0); /* store data */
  41.      fwrite(&cdat, sizeof(cdat), 1, f);
  42.   }
  43.   fclose(f);
  44.   return 0;
  45. }
  46.